package model

import (
	"go-vue/admin/conf"
	"log"
)

type PermissionType string

const (
	PermissionPerson PermissionType = "member"
	PermissionRole   PermissionType = "role"
)

// SystemPermission 系统角色（个人）权限
type SystemPermission struct {
	Type        PermissionType `xorm:"type"`
	RelationId  int64          `xorm:"relation_id"`
	Permissions string         `xorm:"permissions"`
}

func (permission *SystemPermission) One() *SystemPermission {
	exist, err := conf.DbEngine.Get(permission)
	if err != nil {
		log.Println(err)
		return nil
	}
	if !exist {
		return nil
	}
	return permission
}

// Save 保存权限
func (permission *SystemPermission) Save() error {
	_, err := conf.DbEngine.Where("type = ? AND relation_id = ?", permission.Type, permission.RelationId).Delete(&SystemPermission{})
	_, err = conf.DbEngine.Insert(permission)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}

// Save 保存权限
func (permission *SystemPermission) MyPermission() error {
	_, err := conf.DbEngine.Where("type = ? AND relation_id = ?", permission.Type, permission.RelationId).Delete(&SystemPermission{})
	_, err = conf.DbEngine.Insert(permission)
	if err != nil {
		log.Println(err)
		return err
	}
	return nil
}
